<template>
	<view class="catgory-wrap">
		<!-- 标题栏 -->
		<view class="head-nav">
			<u-navbar backIconName borderBottom :background="navbar.background" :backTextStyle="navbar.backTextStyle"
				backText="分类">
				<view class="ma20" @tap="$Router.push({ path: '/pages/goods/list' })">
					<u-search placeholder="搜索" disabled v-model="keyword" :showAction="false" height="46"></u-search>
				</view>
			</u-navbar>
		</view>
		<view class="x-f wrapper-box">
			<!-- 左侧分类列表 -->
			<view class="u-tab-view menu-scroll-view">
				<view class="u_collapse_box">
					<u-collapse accordion :value="accordionVal" @change="change_collapse">
						<u-collapse-item v-for="item in tabbarList" :key="item.id" :title="item.name">
							<view class="child_view" :class="{'active' : nowIndex == index}"
								v-for="(element,index) in item.children" :key="element.id"
								@tap="hand_childType(element,index)">{{ element.name }}</view>
						</u-collapse-item>
					</u-collapse>
				</view>
			</view>

			<!-- 右侧商品列表 -->
			<view class="right-wrap">
				<scroll-view v-if="goodsList.length" scroll-y class="right-box menu-scroll-view" scroll-with-animation
					:scroll-top="scrollTop" @scrolltolower="loadMore">
					<view v-if="tabbarList[currentTab].image" class="category-img-wrap x-c">
						<image class="category-img" :src="tabbarList[currentTab].image" mode="widthFix"></image>
					</view>
					<!-- <view class="category-title">{{ tabbarList[currentTab].name }}</view> -->
					<view class="category-title">{{type_name}}</view>
					<view class="good_box">
						<view class="sh-big-card-wrap " v-for="item in goodsList" :key="item.id">
							<view class="big-goods-card" @tap="jump('/pages/goods/detail/index', { id: item.id })">
								<view class="img-wrap mb20">
									<image class="goods-img" :src="item.image" mode="aspectFill"></image>
									<image class="goods-tag" v-if="item.is_hot && !item.activity"
										:src="$IMG_URL + '/goods/goods_hot_tag.png'" mode=""></image>
									<image class="goods-next" v-if="item.is_next_day_delivery && !item.activity"
										:src="$IMG_URL + '/goods/day5.png'" mode=""></image>
									<image class="goods-tag" v-if="item.activity" :src="tagPath[item.activity_type]"
										mode=""></image>
								</view>
								<view class="goods-title px10 mb10 more-t">
									<!-- <text v-if="item.is_next_day_delivery" style="color: #f5a623;">[次日达] </text> -->
									{{ item.title }}
								</view>
								<view class="goods-time px10 mb20 more-t">{{ item.subtitle }}</view>
								<view class="u-m-b-20 px10" v-if="item.activity_discounts_tags.length">
									<view class="tag-box  u-m-r-10" v-for="(tag, index) in item.activity_discounts_tags"
										:key="index">{{ tag }}</view>
								</view>
								<view class="goods-progress px10 x-f mb10">
									<view class="cu-progress round sm">
										<view class="progress--ing"
											:style="[{ width: getProgress(item.sales, item.stock) }]"></view>
										<view class="round-tag"
											:style="[{ left: getProgress(item.sales, item.stock) }]">
											<image class="round-tag-img" :src="$IMG_URL + '/goods/goods_mini_hot.png'"
												mode=""></image>
										</view>
									</view>
									<view class="googs-send-num ml20">已售{{ item.sales }}件</view>
								</view>
								<view class="price_views px10">
									<view class="price-box">
										<view class="price">{{ item.price }}</view>
										<view class="origin-price ml10">￥{{ item.original_price }}</view>
									</view>
									<view class="cart-box">
										<!-- 单规格 -->
										<view class="" v-if="!item.activity">
											<view v-if="!item.is_sku">
												<button v-if="!isCart(item.id)" @tap.stop="addCart(item.sku_price[0])"
													class="cu-btn cart-btn">加入购物车</button>
												<view class="num-step" v-else>
													<uni-number-box @change="onChangeNum($event, item.sku_price[0])"
														:value="checkCart[item.id].num" :step="1" :min="0"
														:goodsInfo="item" :currentSkuPrice="item.sku_price[0]"
														:disabled="numberDisabled"></uni-number-box>
												</view>
											</view>
											<!-- 多规格 -->
											<button class="cu-btn item-btn sel-sku " @tap.stop="selSku(item)"
												v-else>选规格</button>
										</view>
										<button class="cu-btn item-btn sel-sku" v-else>立即抢购</button>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 加载更多 -->
					<u-loadmore v-if="!isEmpty" height="80rpx" :status="loadStatus" icon-type="flower" color="#ccc" />
				</scroll-view>
				<!-- 空数据 -->
				<u-empty v-if="isEmpty" mode="list"></u-empty>
			</view>
		</view>
		<!-- 规格 -->
		<t-takeout-sku v-if="goodsInfo.id && showSku" v-model="showSku" :goodsInfo="goodsInfo"
			:buyType="'cart'"></t-takeout-sku>
		<!-- 登录提示 -->
		<t-login-modal></t-login-modal>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	export default {
		components: {},
		data() {
			return {
				navbar: {
					backTextStyle: {
						color: '#333',
						'font-size': '35rpx',
						'font-weight': '600'
					},
					background: {
						background: '#fff'
					}
				},
				showSku: false, //是否显示规格弹窗
				isEmpty: false,
				currentTab: 0,
				categoryID: 0, //分类id
				tabbarList: [], //左侧分类列表
				goodsList: [], //商品列表
				goodsInfo: {}, //点击商品详情
				numberDisabled: false, //购物车计数器
				loadStatus: 'loadmore', //loadmore-加载前的状态，loading-加载中的状态，nomore-没有更多的状态
				currentPage: 1,
				lastPage: 1,
				type_name: '',
				query_params: {},
				nowIndex: null,
				accordionVal: ['1'],
				isLoaded: false // 用于标记页面是否已经加载过
			};
		},
		props: {},
		computed: {
			...mapState({
				cartNum: state => state.cart.cartNum,
				cartList: state => state.cart.cartList
			}),
			...mapGetters(['totalCount', 'isSel']),
			// 购物车检测
			checkCart() {
				let obj = {};
				this.cartList.forEach(item => {
					obj[item.goods_id] = {
						num: item.goods_num,
						cartOrderId: item.id
					};
				});
				return obj;
			}
		},
		async onLoad() {
			
		},
		async onShow() {
		
			console.log(uni.getStorageSync('isLoaded'))
			if (!uni.getStorageSync('isLoaded')) {
				// 首次加载时执行的逻辑
				console.log('页面首次加载');
				this.isLoaded = true; // 标记页面已加载
				
				this.type_name = ''
				this.nowIndex = null
				this.accordionVal = []
				await this.getCategory()
				this.query_params = uni.getStorageSync('tab-/pages/index/category')
				let queryCategoryId = Number(this.query_params.id)
				if (this.categoryID != queryCategoryId) {
					this.categoryID = queryCategoryId
				} else {
					this.categoryID = ''
				}
				this.goodsList = []
				await this.getGoodsList()
				this.getCartList()
			} else {
				// 从其他页面返回时执行的逻辑
				console.log('页面返回，不刷新');
				
			}

		},
		destroyed() {
			this.type_name = ''
			this.nowIndex = null
		},
		methods: {
			...mapActions(['getCartList', 'changeCartList', 'addCartGoods']),
			// 跳转详情
			toGoodDetail(id) {
				this.$Router.push({
					path: '/pages/goods/detail/index',
					query: {
						id: id
					}
				});
			},

			//点击商品一级分类
			change_collapse(e) {
				console.log('222', e)
				this.nowIndex = null
				this.accordionVal = e
			},

			//点击商品二级分类
			hand_childType(item, i) {
				uni.hideLoading()
				this.currentPage = 1
				this.goodsList = []
				this.nowIndex = i
				this.categoryID = item.id
				this.type_name = item.name
				setTimeout(() => {
					this.getGoodsList(this.categoryID)
				}, 500)
			},

			// 百分比
			getProgress(sales, stock) {
				let unit = '';
				if (stock + sales > 0) {
					let num = (sales / (sales + stock)) * 100;
					unit = num.toFixed(2) + '%';
				} else {
					unit = '0%';
				}
				return unit;
			},

			// 加载更多
			loadMore() {
				if (this.currentPage < this.lastPage) {
					this.currentPage += 1;
					this.getGoodsList();
				}
			},

			// 获取分类
			async getCategory() {
				const res = await this.$api('category.info', {
					id: 0
				})
				this.tabbarList = res.data ? res.data : []
			},

			// 获取商品列表
			getGoodsList(goodsid) {
				let that = this;
				that.loadStatus = 'loading'
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				that.$api('goods.lists', {
					category_id: that.categoryID || 0,
					page: that.currentPage
				}).then(res => {
					uni.hideLoading()
					if (res.code === 1) {
						that.goodsList = [...that.goodsList, ...res.data.data]
						that.isEmpty = !that.goodsList.length
						that.lastPage = res.data.last_page
						that.loadStatus = that.currentPage < res.data.last_page ? 'loadmore' : 'nomore';
					}
				})
			},

			// 点击左边的栏目切换
			async swichMenu(index) {
				if (index == this.currentTab) return;
				this.currentTab = index;
				this.categoryID = this.tabbarList[index].id;
				uni.setStorageSync('tab-/pages/index/category', {
					id: this.categoryID
				});
				this.currentPage = 1;
				this.lastPage = 1;
				this.goodsList = [];
				await this.getGoodsList();
			},

			// 加入购物车
			addCart(goods) {
				let token = uni.getStorageSync('token')
				console.log('判断用户是否登录', token)
				if (!token) {
					this.$tools.toast('请登录后再操作')
					return
				}
				if (goods.stock <= 0) {
					this.$tools.toast('库存不足')
					return;
				}
				let obj = {
					goods_id: goods.goods_id,
					goods_num: 1,
					sku_price_id: goods.id,
					goods_price: goods.price
				};
				let confirmGoodsList = {
					list: [obj],
					from: 'goods'
				};
				this.addCartGoods(confirmGoodsList).then(res => {
					if (res.code === 1) {
						this.$tools.toast(res.msg);
					}
				});
			},
			// 检测商品在购物车中的下标
			checkGoodsIndex(id) {
				let cIndex = 0;
				this.cartList.forEach((item, index) => {
					if (id == item.goods_id) {
						cIndex = index;
					}
				});
				return cIndex;
			},
			// 更改商品数
			async onChangeNum(e, goods) {
				let gIndex = this.checkGoodsIndex(goods.goods_id);
				if (e != this.checkCart[goods.goods_id].num) {
					this.numberDisabled = true;
					uni.showLoading({
						mask: true
					});
					if (e <= 0) {
						await this.changeCartList({
							ids: [this.checkCart[goods.goods_id].cartOrderId],
							art: 'delete'
						});
					} else {
						this.$set(this.cartList[gIndex], 'goods_num', +e);
						await this.changeCartList({
							ids: [this.checkCart[goods.goods_id].cartOrderId],
							goodsNum: +e,
							art: 'change'
						});
					}
					this.numberDisabled = false;
					await uni.hideLoading();
				}
			},
			// 检测是否为购物车商品
			isCart(id) {
				let goodsId = id + '';
				return Object.keys(this.checkCart).includes(goodsId);
			},

			// 添加购物车
			async selSku(info) {
				this.goodsInfo = {};
				this.getGoodsDetail(info.id);
				this.showSku = true;
			},
			// 商品详情
			getGoodsDetail(id) {
				let that = this;
				that.$api('goods.detail', {
					id: id
				}).then(res => {
					if (res.code === 1) {
						that.goodsInfo = res.data;
					}
				});
			},

			// 路由跳转
			jump(path, parmas) {
				this.$Router.push({
					path: path,
					query: parmas
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	// 最外层结构包裹
	.catgory-wrap {
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;
	}

	.wrapper-box {
		flex: 1;
		display: flex;
		overflow: hidden;

		// 左侧menu
		.u-tab-view {
			width: 260rpx;
			height: 100%;

			.u-tab-item {
				height: 110rpx;
				background: #f6f6f6;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 26rpx;
				color: #444;
				font-weight: 400;
				line-height: 1;
			}

			.u-tab-item-active {
				position: relative;
				color: #000;
				font-size: 30rpx;
				font-weight: bold;
				background: #fff;
			}

			.u-tab-item-active::before {
				content: '';
				position: absolute;
				border-left: 4px solid $t-mainColor;
				height: 32rpx;
				left: 0;
				top: 39rpx;
			}

			.u_collapse_box {
				padding: 0 0 0 20rpx;

				.child_view {
					padding-left: 20rpx;
					height: 60rpx;
					line-height: 60rpx;

					&.active {
						color: #ff0000;
					}
				}
			}
		}
	}

	// 右侧商品滚动
	.right-wrap {
		background-color: #fff;
		height: 100%;
		width: 100%;

		.category-img-wrap {
			margin: 20rpx;
			width: 554rpx;
			min-height: 200rpx;
			border-radius: 20rpx;
			overflow: hidden;
			box-shadow: 0 0 8rpx 2rpx rgba(199, 199, 199, 0.3);

			.category-img {
				width: 100%;
				background-color: #ccc;
				min-height: 200rpx;
				border-radius: 20rpx;
			}
		}

		.category-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #000;
			margin: 20rpx;
		}

		.good_box {
			overflow: hidden;
			padding: 0 20rpx;

			.sh-big-card-wrap {
				width: 48%;
				float: left;
				margin-bottom: 20rpx;

				&:nth-child(2n) {
					float: right;
				}
			}
		}

		.right-box {
			height: 100%;
		}
	}

	.big-goods-card {
		background-color: #fff;
		border-radius: 20rpx;
		width: 100%;
		box-shadow: 0 0 8rpx 2rpx rgba(199, 199, 199, 0.3);
		padding-bottom: 10rpx;

		.img-wrap {
			position: relative;
			width: 100%;
			padding-bottom: 100%; // 基于宽度实现1:1比例（根据实际图片比例调整）
			border-radius: 20rpx 20rpx 0 0;
			overflow: hidden;

			.goods-img {
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
				left: 0;
			}

			.goods-day {
				position: absolute;
				bottom: -18rpx;
				left: 1rpx;
				width: 120rpx;
				height: 100rpx;
				z-index: 2;
			}

			.goods-tag {
				position: absolute;
				top: 16rpx;
				left: 16rpx;
				width: 88rpx;
				height: 88rpx;
				z-index: 2;
			}

			.goods-next {
				position: absolute;
				top: 16rpx;
				right: 16rpx;
				width: 88rpx;
				height: 88rpx;
				z-index: 2;
			}
		}

		.goods-title {
			font-size: 30rpx;
			font-weight: bold;
			color: #333333;
			height: 72rpx;
			line-height: 36rpx;
		}

		.goods-time {
			font-size: 24rpx;
			font-weight: 400;
			color: #999999;
			height: 72rpx;
			line-height: 36rpx;
		}

		.tag-box {
			border: 1px solid #ff0000;
			display: inline-block;
			font-size: 20rpx;
			line-height: 30rpx;
			padding: 0 10rpx;
			color: #ff0000;
			border-radius: 8rpx;
		}

		.goods-progress {
			justify-content: space-between;

			.cu-progress {
				width: 100rpx;
				height: 20rpx;
				background: rgba(#ff6361, 0.2);
				overflow: visible;
				position: relative;

				.progress--ing {
					background: #ff6361;
					border-radius: 20rpx;
				}

				.round-tag {
					position: absolute;
					bottom: 0;
					width: 20rpx;
					height: 28rpx;
					margin-left: -10rpx;

					.round-tag-img {
						width: 20rpx;
						height: 28rpx;
					}
				}
			}

			.googs-send-num {
				font-size: 24rpx;
				font-weight: 400;
				color: #bebebe;
			}
		}

		.price-box {
			vertical-align: text-bottom;
			display: flex;
			justify-content: space-between;

			.price {
				font-size: 36rpx;
				color: $t-priceColor;
				font-weight: 600;

				&::before {
					content: '￥';
					font-size: 28rpx;
				}

				vertical-align: text-bottom;
			}

			.origin-price {
				vertical-align: text-bottom;
				font-size: 26rpx;
				font-weight: 400;
				text-decoration: line-through;
				color: #c4c4c4;
				margin-top: 6rpx;
			}
		}

		::v-deep .cart-box {
			text-align: center;
			margin-top: 10rpx;

			.cart-btn,
			.sel-sku {
				width: 100%;
				height: 58rpx;
				background: linear-gradient(to right, $t-gradualColor, $t-mainColor);
				border-radius: 30rpx;
				padding: 0;
				font-size: 26rpx;
				font-weight: 500;
				color: #ffffff;
			}

			.uni-numbox {
				justify-content: center;
			}
		}
	}
</style>